<template>
  <div class="product-detail">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <el-empty
        :description="error"
        :image-size="200"
      >
        <template #extra>
          <el-button type="primary" @click="router.push('/products')">
            {{ $t('返回') }}
          </el-button>
        </template>
      </el-empty>
    </div>

    <!-- 商品详情内容 -->
    <template v-else>
      <div class="container">
        <div class="product-grid">
          <!-- 左侧图片区 -->
          <div class="product-gallery">
            <div class="main-image">
              <el-image
                :src="productData.image"
                fit="contain"
                :z-index="9999"
                preview-teleported
                :preview-src-list="[productData?.image || '']"
              />
            </div>
          </div>

          <!-- 中间商品信息区 -->
          <div class="product-info">
            <h1 class="title">{{ productData.name }}</h1>
<!--            <div class="brand">-->
<!--              品牌：<a :href="'/brand/' + productData.brandId">{{ productData.brand }}</a>-->
<!--            </div>-->

            <div class="divider"></div>

            <div class="price-section">
              <div class="price-row">
                <span class="label">{{ $t('价格') }}：</span>
                <span class="current-price">{{ langStore.languageSymbol }}{{ productData.price*langStore.languageRate }}</span>
              </div>
              <div class="original-price" v-if="productData.price">
                {{ $t('原价') }}：<span class="strikethrough">{{ langStore.languageSymbol }}{{ productData.price*langStore.languageRate }}</span>
              </div>
            </div>

            <div class="divider"></div>
          </div>

          <!-- 右侧购买区 -->
          <div class="buy-box">
            <div class="price pricew">{{ $t('折扣') }}: {{ langStore.languageSymbol }}{{ userVipLevelRate*langStore.languageRate }}</div>
            <div class="price pricew">{{ $t('原价') }}: {{ langStore.languageSymbol }}{{ productData.price*langStore.languageRate*productNum }}</div>
            <div class="price">{{ $t('支付金额') }}: {{ langStore.languageSymbol }}{{ productData.price*langStore.languageRate*productNum* (1 - userVipLevelRate) }}</div>

            <!-- 库存状态 -->
<!--            <div class="stock-info">-->
<!--              <div class="stock-status" :class="stockStatusClass">-->
<!--                <el-icon v-if="productData.stock > 0"><Check /></el-icon>-->
<!--                {{ stockStatusText }}-->
<!--              </div>-->
<!--              <div class="stock-quantity" v-if="productData.stock > 0 && productData.stock <= 20">-->
<!--                仅剩 {{ productData.stock }} 件-->
<!--              </div>-->
<!--            </div>-->

            <div class="quantity-selector">
              <span class="label">{{ $t('数量') }}</span>
              <el-input-number
                v-model="productNum"
                :min="1"
                :max="9999"
                size="large"
              />
            </div>


            <div class="action-buttons">
              <el-button
                class="add-to-cart"
                @click="addToCart"
              >
                {{ $t('加入购物车') }}
              </el-button>

              <el-button
                type="primary"
                class="buy-now"
                @click="buyNow"
              >
                {{ $t('立即购买') }}
              </el-button>
            </div>

            <!-- <div class="secure-transaction">
              <el-icon><Lock /></el-icon>
              安全交易
            </div> -->
          </div>
        </div>

        <!-- 商品详情标签页 -->
        <div class="product-tabs">
          <el-tabs v-model="activeTab">
            <el-tab-pane :label="$t('优惠券详情')" name="detail">
              <div class="detail-content" v-html="productData.detail"></div>
            </el-tab-pane>

<!--            <el-tab-pane label="规格参数" name="specs">-->
<!--              <div class="specs-content">-->
<!--                <el-descriptions :column="1" border>-->
<!--                  <el-descriptions-item-->
<!--                    v-for="(spec, key) in productData.specs"-->
<!--                    :key="key"-->
<!--                    :label="key"-->
<!--                  >-->
<!--                    {{ spec }}-->
<!--                  </el-descriptions-item>-->
<!--                </el-descriptions>-->
<!--              </div>-->
<!--            </el-tab-pane>-->
          </el-tabs>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import { Lock } from '@element-plus/icons-vue'
import {ApiAddCart, ApiBuyNow, ApiCommodityDetail} from "@/api/commodity.js";
import useCartStore from "@/store/modules/cart.js";
import useUserStore from '@/store/modules/user'
import {useI18n} from "vue-i18n";
const { t } = useI18n();
import useLangStore from '@/store/modules/lang'
const langStore = useLangStore()
const userStore = useUserStore();

//折扣率
const userVipLevelRate = ref('0');
const userVipLevel = ref('0');
const buyLock = ref('0')

//获取个人信息
const getInfouser = async () => {
  const getInfouserStore = await userStore.getInfo();
  userVipLevelRate.value = getInfouserStore.data?.member?.userVipLevelRate || 0;
  userVipLevel.value = getInfouserStore.data?.member?.userVipLevel || 0;
  buyLock.value = getInfouserStore.data?.member?.buyLock || 0;

}
const cartStore = useCartStore()
const route = useRoute()
const router = useRouter()
const productId = route.params.id

const loading = ref(true)
const error = ref('')
const productNum = ref(1)
const activeTab = ref('detail')

// 商品数据
const productData = ref({})

const loadProductDetail = async () => {
  try {
    loading.value = true
    error.value = ''
    const { data } = await ApiCommodityDetail({ productId })
    productData.value = data
    const detail = productData.value.detail ? JSON.parse(productData.value.detail) : {}
    productData.value.detail = detail?.des || ''
  } catch (err) {
    console.error('Failed to load product detail:', err)
    error.value = err instanceof Error ? err.message : t('加载详情失败')
  } finally {
    loading.value = false
  }
}

const addToCart = async () => {
  const loading = ElLoading.service()
  try {
    await ApiAddCart({
      productId: productData.value.id,
      productNum: productNum.value
    })
    await cartStore.getCartList()
    loading.close()
    ElMessage.success(t('已添加到购物车'))
  } catch (error) {
    loading.close()
    console.error('Failed to add to cart:', error)
    ElMessage.error(t('添加购物车失败，请重试'))
  }
}

const buyNow = () => {
  if(buyLock.value != '0'){
    return ElMessage.error(t('账户无法购买，请联系客服'));
  }
  ElMessageBox.prompt(t('请输入资金密码'), t('提示'), {
    confirmButtonText: t('确定'),
    cancelButtonText: t('取消'),
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false,
    inputType: 'password',
    inputPattern: /^\d{6}$/,
    inputErrorMessage: t('资金密码为6位数字')
  }).then(({ value }) => {
    // console.log('支付密码是' + value)
    const loading = ElLoading.service()
    ApiBuyNow({
      productId: productData.value.id,
      num: productNum.value,
      assetPwd: value
    }).then(() => {
      ElMessage.success(t('购买成功'))
    }).finally(() => {
      loading.close()
    })
  }).catch(() => {
    console.log('取消输入')
  });
}

onMounted(() => {
  getInfouser();
  loadProductDetail();
})
</script>

<style lang="scss" scoped>
@use './style/detail.scss';

.loading-container,
.error-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin: 20px 0;
}

.error-container {
  flex-direction: column;
  text-align: center;
}

.amazon-choice {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  color: #232f3e;

  i {
    color: #FF9900;
    font-size: 18px;
  }

  span {
    font-size: 14px;
    font-weight: 500;
  }
}
</style>
